import './common/polyfills';
import {
  AppBootstraper
} from './boot';
import './style.scss';
import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import {
  AppConsts
} from './store/appConsts';
import AppContainer from './containers/AppContainer'
import zhCN from 'antd/lib/locale-provider/zh_CN';
import {
  browserHistory
} from 'react-router'
import 'moment/locale/zh-cn';
import moment from 'moment';
moment.locale('zh-cn');

import {
  Helper
} from './common/helper'

// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__;


const store = createStore(initialState)


// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')

let render = () => {
  const routes = require('./routes/index').default(store)

  ReactDOM.render( <
    AppContainer store = {
      store
    }
    routes = {
      routes
    }
    history = {
      browserHistory
    }
    />,
    MOUNT_NODE
  )
}

// ========================================================
// Developer Tools Setup
// ========================================================
if (__DEV__) {
  if (window.devToolsExtension) {
    window.devToolsExtension.open()
  }
}

// This code is excluded from production bundle
if (__DEV__) {
  if (module.hot) {
    // Development render functions
    const renderApp = render
    const renderError = (error) => {
      const RedBox = require('redbox-react').default

      ReactDOM.render( < RedBox error = {
          error
        }
        />, MOUNT_NODE)
      }

      // Wrap render in try/catch
      render = () => {
        try {
          renderApp()
        } catch (error) {
          console.error(error)
          renderError(error)
        }
      }

      // Setup hot module replacement
      module.hot.accept('./routes/index', () =>
        setImmediate(() => {
          ReactDOM.unmountComponentAtNode(MOUNT_NODE)
          render()
        })
      )
    }
  }

  // ========================================================
  // Go!
  // ========================================================
  AppBootstraper.run().then(() => {
    Cookies.set(AppConsts.cookie_cultureName, 'zh-CN');
    Cookies.set(AppConsts.cookie_tenant_id, '1');
  }).then(() => render()).then(() => {
    //登录判断
    let token = Helper.getToken();
    if (token) {
      //服务器验证token
      AppBootstraper.getAll();
    }
  }).then(() => {
    window.onhashchange = function(e) {
      console.log('onhashchange:', e)
    }
  });
